package com.nbb.demo.redissondemo.controller;

import cn.hutool.http.HttpUtil;
import lombok.SneakyThrows;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * @description:
 * @author: Jerry
 * @time: 2021/3/15 14:38
 */
@RestController
public class AppController {

    @Autowired
    private RedissonClient redissonClient;

    public static int num = 100;

    @ResponseBody
    @GetMapping("/order")
    @SneakyThrows()
    public String order() {
        RLock lock = redissonClient.getLock("test:redissonLock");
//        lock.lock();
//        if (lock.tryLock()) {
        if (lock.tryLock(60, 15,TimeUnit.SECONDS)) {
            if (num >= 0) {
                Thread.sleep(10);
                System.out.println("order: " + num);
                String res = "" + num;
                num--;
//                lock.unlock();
                Thread.sleep(20000);
                return res;
            }
        }
        return "null";
    }

    public static void main(String[] args) throws InterruptedException {
        for (int i = 0; i < 1000; i++) {
//            Thread.sleep(100);
            new Thread(() -> {
                String result = HttpUtil.get("localhost:8888/order");
                System.out.println(result);
            }).start();
        }
    }
}
